"""
审计日志模型
用于记录所有用户操作，便于审计和追踪
"""
from pydantic import BaseModel, Field
from typing import Optional, Dict, Any
from datetime import datetime
from enum import Enum


class AuditStatus(str, Enum):
    """审计状态"""
    SUCCESS = "success"
    FAILED = "failed"
    PENDING = "pending"


class ResourceType(str, Enum):
    """资源类型"""
    USER = "user"
    NOTE = "note"
    CERTIFICATE = "certificate"
    DOMAIN = "domain"
    DNS_RECORD = "dns_record"
    CLUSTER = "cluster"
    METRIC = "metric"
    ALERT_RULE = "alert_rule"
    LOG_PROJECT = "log_project"
    HOST = "host"
    DATABASE = "database"


class AuditAction(str, Enum):
    """审计动作"""
    # 通用操作
    CREATE = "create"
    UPDATE = "update"
    DELETE = "delete"
    READ = "read"
    LIST = "list"
    
    # 认证操作
    LOGIN = "login"
    LOGOUT = "logout"
    REGISTER = "register"
    CHANGE_PASSWORD = "change_password"
    CHANGE_EMAIL = "change_email"
    
    # 管理操作
    BAN_USER = "ban_user"
    UNBAN_USER = "unban_user"
    
    # 证书操作
    APPLY_CERTIFICATE = "apply_certificate"
    RENEW_CERTIFICATE = "renew_certificate"
    DOWNLOAD_CERTIFICATE = "download_certificate"
    
    # DNS 操作
    ADD_DOMAIN = "add_domain"
    ADD_DNS_RECORD = "add_dns_record"
    UPDATE_DNS_RECORD = "update_dns_record"
    
    # 集群操作
    DEPLOY_APP = "deploy_app"
    SCALE_APP = "scale_app"
    
    # 其他
    BACKUP = "backup"
    RESTORE = "restore"
    EXPORT = "export"
    IMPORT = "import"


class AuditLogBase(BaseModel):
    """审计日志基础模型"""
    user_id: str = Field(..., description="用户ID")
    action: AuditAction = Field(..., description="操作动作")
    resource_type: ResourceType = Field(..., description="资源类型")
    resource_id: Optional[str] = Field(None, description="资源ID")
    status: AuditStatus = Field(..., description="操作状态")
    request_id: str = Field(..., description="请求ID")
    ip_address: Optional[str] = Field(None, description="IP地址")
    user_agent: Optional[str] = Field(None, description="用户代理")
    details: Optional[Dict[str, Any]] = Field(default_factory=dict, description="详细信息")
    error_message: Optional[str] = Field(None, description="错误信息")


class AuditLogCreate(AuditLogBase):
    """创建审计日志"""
    pass


class AuditLogInDB(AuditLogBase):
    """数据库中的审计日志"""
    id: str
    timestamp: datetime = Field(default_factory=datetime.utcnow)
    
    class Config:
        from_attributes = True


class AuditLogOut(AuditLogBase):
    """返回的审计日志"""
    id: str
    timestamp: datetime
    
    class Config:
        from_attributes = True


class AuditLogQuery(BaseModel):
    """审计日志查询条件"""
    user_id: Optional[str] = None
    action: Optional[AuditAction] = None
    resource_type: Optional[ResourceType] = None
    resource_id: Optional[str] = None
    status: Optional[AuditStatus] = None
    request_id: Optional[str] = None
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None
    skip: int = Field(default=0, ge=0)
    limit: int = Field(default=20, ge=1, le=100)

